package com.java.simple.study.juc;

/**
 * @author zhoujunlin
 * @date 2023年05月11日 15:15
 * @desc
 */
public class MemoryLeakTest {

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                TestClass testClass = new TestClass(i);
                testClass.print();
                // java.lang.OutOfMemoryError: Java heap space
                // 并没有垃圾回收掉  仍旧被threadlocal引用着
                //testClass = null;
                testClass.threadLocal.remove();
            }
        }).start();
    }

    static class TestClass {
        private final int id;
        private final int[] arr;
        private final ThreadLocal<TestClass> threadLocal;

        public TestClass(int id) {
            this.id = id;
            // 大对象  内存泄露会造成oom
            this.arr = new int[1000000];
            this.threadLocal = new ThreadLocal();
            threadLocal.set(this);
        }

        public void print() {
            System.out.println(this.threadLocal.get().id);
        }
    }

}
